package com.ddtech.platform;

import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

public class AbstractClient {
	
	private static final String POINT_PACK_BASE ="api/pack";
	
	private static final String POINT_TEST = "/ping";
	
	/**
	 * 
	 */
	protected final String baseUrl;
	
	/**
	 * 
	 * @param serverUrl
	 */
	public AbstractClient(String serverUrl){
		baseUrl = serverUrl;
		//确定服务器活着
		this.doTest();
	}
	
	/**
	 * 
	 */
	protected void doTest(){
		String ep = getEndPointUrl(POINT_TEST);
		int status;
		try {
			status = Unirest.get(ep).asJson().getStatus();
			if(status!=200){
				throw new RuntimeException("无法连接服务器，请检查服务器地址，或确定有权限访问服务器.返回码："+status);
			}
		} catch (UnirestException e) {
			throw new RuntimeException("无法连接服务器，请检查服务器地址，或确定有权限访问服务器.",e);
		}
	}
	
	protected String getEndPointUrl(String endPoint){
		return this.baseUrl+POINT_PACK_BASE+endPoint;
	}
	
	
	protected String toJson(Map<String,String> params){
		Iterator<String> keys = params.keySet().iterator();
		JSONObject o = new JSONObject();
		while(keys.hasNext()){
			String key = keys.next();
			o.put(key, params.get(key));
		}
		return o.toString();
	}
	
	/**
	 * 关闭client
	 * @throws IOException
	 */
	public void shutdown(){
//		try {
//			Unirest.shutdown();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
	}
}
